import React, {Component} from 'react';
import {Image, ScrollView, FlatList, Text, TouchableOpacity, View, AsyncStorage} from 'react-native';
import {BasicStyle} from "../../../style/BasicStyle";
import {ShopListStyle} from "../../../style/ShopStyle/ShopListStyle";
import {ShopStyle} from "../../../style/ShopStyle/ShopStyle";
import Spinner from 'react-native-loading-spinner-overlay';
import Toast from '@remobile/react-native-toast';
import Swiper from 'react-native-swiper';
import FetchUtils from './../../utils/FetchUtils'
import utils from './../../utils/utils';

export default class ShopList extends Component {

    static navigationOptions = ({navigation, screenProps}) => ({
        headerStyle: {
            backgroundColor: '#F6F6F6',
        },
    });

    constructor(prop) {
        super(prop);
        this.nowType = null;
        this.page = 0;
        this.size = 20;
        this.state = ({
            loadingStatus: false,
            isShowTypeButs: true,
            typeButs: [],
            listData: [],
            lastStatus: false,
            page: 0,
            size: 20,
        })
    }

    componentDidMount() {
        if (this.props.navigation.state.params) {
            this.setState({
                isShowTypeButs: false,
            });
            this.nowType = this.props.navigation.state.params.resMark;

            AsyncStorage.getItem("XToken").then((xToken) => {
                if (!this.state.lastStatus) {
                    this.setState({loadingStatus: true});
                    let params = {
                        page: this.state.page,
                        size: this.state.size,
                        type: this.nowType,
                    };
                    FetchUtils.getWithHeader(utils.apiUrl + '/shop/typeList', xToken, params, (res) => {
                        if (res.code === 200) {
                            this.setState({
                                listData: res.apiData.content,
                                page: res.apiData.number,
                                size: res.apiData.size,
                                loadingStatus: false,
                            });
                        } else {
                            this.setState({
                                loadingStatus: false,
                            });
                            Toast.showShortTop(res.apiData);
                        }
                    })
                }
            });
        } else {
            let params = ({
                size: this.state.size,
                page: this.state.page,
            });
            AsyncStorage.getItem("XToken").then((xToken) => {
                FetchUtils.getWithHeader(utils.apiUrl + '/shop/mainTypeList', xToken, params, (res) => {
                    if (res.code === 200) {
                        this.setState({
                            typeButs: res.apiData.buts.content,
                            listData: res.apiData.list.content,
                            page: res.apiData.list.number,
                            lastStatus: res.apiData.list.last,
                        });
                        /*按钮变色*/
                        this._clickTypeButs('buts-' + res.apiData.buts.content[0].id + '-' + res.apiData.buts.content[0].title, res.apiData.buts.content[0].title);
                        this.nowType = res.apiData.buts.content[0].title;
                    }
                })
            })
        }

    }

    render() {
        return (
            <View style={[BasicStyle.containerView, ShopListStyle.containerView]}>
                {this.state.isShowTypeButs ?
                    < View style={ShopListStyle.typeButsView}>
                        {this._makeTypeButs(this.state.typeButs)}
                    </View>
                    :
                    null
                }
                <ScrollView
                    showsVerticalScrollIndicator={false}
                    showsHorizontalScrollIndicator={false}
                    removeClippedSubviews={false}
                    onMomentumScrollEnd={this._onScroll.bind(this)}
                >
                    <Spinner visible={this.state.loadingStatus} textContent={""} textStyle={{color: '#FFF'}}/>

                    <View style={ShopStyle.listView}>
                        {this._makelistItem(this.state.listData)}
                    </View>
                    <Image style={BasicStyle.endImg} source={require('./../../../img/end.png')}/>

                </ScrollView>
            </View>
        )
    }

    /*生成头部的分类按钮*/
    _makeTypeButs = (buts) => {
        return buts.map((item) => {
            return <TouchableOpacity key={item.id}
                                     onPress={this._clickTypeButs.bind(this, 'buts-' + item.id + '-' + item.title, item.title)}>
                <Text ref={'buts-' + item.id + '-' + item.title} style={ShopListStyle.typeButsText}>{item.title}</Text>
            </TouchableOpacity>
        })
    };

    /*头部的分类按钮点击事件*/
    _clickTypeButs = (but, title) => {
        /*按钮改变颜色*/
        let refButs = this.state.typeButs.map((item) => {
            return 'buts-' + item.id + '-' + item.title;
        });
        utils.removeByValue(refButs, but);
        refButs.map((item) => {
            this.refs[item].setNativeProps({
                style: {
                    color: '#A0A0A0',
                }
            })
        });
        this.refs[but].setNativeProps({
            style: {
                color: '#000',
            }
        });
        /*将this中的nowType改变，重置page，size*/
        this.nowType = title;
        this.setState({
            page: this.page,
            size: this.size,
            lastStatus: false,
        });
        /*重新请求数据*/
        AsyncStorage.getItem("XToken").then((xToken) => {
            if (!this.state.lastStatus) {
                this.setState({loadingStatus: true});
                let params = {
                    page: this.state.page,
                    size: this.state.size,
                    type: this.nowType,
                };
                FetchUtils.getWithHeader(utils.apiUrl + '/shop/typeList', xToken, params, (res) => {
                    if (res.code == 200) {
                        this.setState({
                            listData: res.apiData.content,
                            page: res.apiData.number,
                            size: res.apiData.size,
                            loadingStatus: false,
                        });
                    } else {
                        this.setState({
                            loadingStatus: false,
                        });
                        Toast.showShortTop(res.apiData);
                    }
                })
            }
        });

    };

    /*生成列表item*/
    _makelistItem(list) {
        let resultList = list.map((item, index) => {
            return <TouchableOpacity key={item.id} onPress={() => {
                let {navigate} = this.props.navigation;
                navigate('ShopDetailNav',{productId: item.id})
            }}
                                     style={[ShopStyle.listItemView, index % 2 === 0 ? {paddingRight: utils.autoWidth(1)} : null]}>
                <Image
                    style={ShopStyle.listItemViewImg}
                    source={{uri: utils.qiniuUrl + item.mainImg + utils.qiniu500Url}}></Image>

                <View style={ShopStyle.listItemTextView}>
                    <Text style={ShopStyle.listTitleViewText}>{item.name}</Text>
                    <View style={{flexDirection: 'row'}}>
                        <Text style={[ShopStyle.listTitleMarkViewText, {
                            textDecorationLine: 'line-through',
                            color: '#A0A0A0'
                        }]}>{item.oldPrice ? "¥ " + item.oldPrice : ""}</Text>
                        <Text
                            style={ShopStyle.listTitleMarkViewText}>{item.nowPrice ? "¥ " + item.nowPrice : ""}</Text>
                    </View>
                </View>
            </TouchableOpacity>
        });
        return resultList;
    }

    /*scrollView滑动方法*/
    _onScroll(event) {
        let y = event.nativeEvent.contentOffset.y;//滑动距离
        let height = event.nativeEvent.layoutMeasurement.height;//scrollView高度
        let contentHeight = event.nativeEvent.contentSize.height;//scrollView contentSize高度
        if (y + height >= contentHeight) {
            AsyncStorage.getItem("XToken").then((xToken) => {
                if (!this.state.lastStatus) {
                    this.setState({loadingStatus: true});
                    let params = {
                        page: this.state.page + 1,
                        size: this.state.size,
                        type: this.nowType,
                    };
                    FetchUtils.getWithHeader(utils.apiUrl + '/shop/typeList', xToken, params, (res) => {
                        if (res.code == 200) {
                            this.setState({
                                listData: this.state.listData.concat(res.apiData.content),
                                page: res.apiData.number,
                                size: res.apiData.size,
                                loadingStatus: false,
                            });
                        } else {
                            this.setState({
                                loadingStatus: false,
                            });
                            Toast.showShortTop(res.apiData);
                        }
                    })
                }
            });
        } else {
            this.setState({loadingStatus: false})
        }
    }

}